<?php

namespace App\Models\HongBao;

use App\Jobs\SendReceiveHongBaoMsgJob;
use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\Msg;
use App\Models\BaseModel;
use App\Models\Config\Config;

class HongBao extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'template_id',
        'type',
        'status',
        'point',
        'limit_point',
        'money',
        'limit_money',
        'end_at',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [];

    protected $dateFormat = 'U';

    protected $table = 'hong_bao';

    /**
     * 关联商家
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function shop(){
        return $this->hasOne('App\Models\Shop\Shop', 'shop_id', 'shop_id');
    }

    /**
     * 获取今天红包领取数
     * @param $user_id
     * @param $template_id
     * @return mixed
     */
    public function dailyHongBaoAddedNum($user_id, $template_id){
        $start = strtotime(date('Y-m-d', time()));
        $end = $start + 86399;
        return $this->where('user_id', $user_id)
            ->where('template_id', $template_id)
            ->where('created_at', '>=', $start)
            ->where('created_at', '<=', $end)
            ->count();
    }

    /**
     * 检查红包来源
     * @param $user_id
     * @param $origin
     * @return mixed
     */
    public function checkOrigin($user_id, $origin){
        return $this->where('user_id', $user_id)
            ->where('origin', $origin)
            ->count();
    }

    /**
     * 获取红包列表
     * @param $page
     * @param $size
     * @param $type
     * @param $status
     * @param $user_id
     * @return array
     */
    public function getHongBaos($page, $size, $type, $status, $user_id){
        $data = [];
        $time = time();
        $sql = $this->where('user_id', $user_id);
        if(!empty($type)){
            $sql = $sql->where('type', $type);
        }
        switch($status){
            case 1:
                $sql = $sql->where('status', 0)
                    ->where('end_at', '>=', $time);
                break;
            case 2:
                $sql = $sql->where('status', 1)
                    ->OrWhere('end_at', '<=', $time);
                break;
            default:
                return [];
        }
        $data['list'] = $sql->forPage($page, $size+1)
            ->orderBy('end_at', 'asc')
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }

    /**
     * 添加预设红包
     * @param $config_key
     * @param $user_id
     * @param $origin
     * @return int
     */
    public function addConfigHongBao($config_key, $user_id, $origin){
        $config = new Config();
        $template = new HongBaoTemplate();
        $config = $config->where('key', $config_key)->firstOrFail();
        if(empty($config)){
            return 50001;
        }
        $template = $template->getTemplateById($config['value']);
        if(empty($template)){
            return 50001;
        }
        if($template['only_once']){
            if(!empty($this->where('user_id', $user_id)->where('template_id', $template['id'])->first())){
                return 50002;
            }
        }else{
            if($this->dailyHongBaoAddedNum($user_id, $template['id']) >= $template['daily_limit'] && $template['daily_limit']){
                return 50002;
            }
            if($this->checkOrigin($user_id, $origin)){
                return 50004;
            }
        }
        switch($template['type']){
            case 1:
                $this->user_id = $user_id;
                $this->template_id = $template['id'];
                $this->origin = $origin;
                $this->type = 1;
                $this->end_at = strtotime(date('Y-m-d', time()+604800));
                $this->save();
                break;
            case 2:
                //todo
                return 50001;
                break;
            case 3:
                //todo
                return 50001;
                break;
            default:
                return 50001;
                break;
        }
//        Easemob::singleton()->sendText(6, 'users', [$user_id], Msg::receive_hong_bao(), ['user_id'=>6]);
        dispatch(new SendReceiveHongBaoMsgJob($user_id));
        return 200;
    }

    /**
     * 重置红包
     * @param $id
     */
    public function refill($id){
        $hongBao = $this->where('id', $id)->first();
        if(!empty($hongBao)){
            $hongBao->status = 0;
            $hongBao->save();
        }
    }

    /**
     * 添加模板红包
     * @param $user_id
     * @param $origin
     * @param HongBaoTemplate $hbt
     * @param int $city_id
     * @param int $shop_id
     * @param int $consumption
     * @return bool 成功返回true
     */
    public function addTemplateHongBao($user_id, $origin, HongBaoTemplate $hbt=null, $city_id=0, $shop_id=0, $consumption=0){
        $hongBaoTemplate = new HongBaoTemplate();
        $hongBao = new HongBao();
        if(empty($hbt)){
            $hbt = $hongBaoTemplate
                ->whereIn('agent_city_id', [$city_id, 0])
                ->whereIn('shop_id', [$shop_id, 0])
                ->where('min_consumption', '<=', $consumption)
                ->where('max_consumption', '>=', $consumption)
                ->where('status', 1)
                ->orderBy('priority', 'desc')
                ->first();
        }
        if(empty($hbt)){
            return false;
        }
        if($hbt->only_once){
            if(!empty($this->where('user_id', $user_id)->where('template_id', $hbt->id)->first())){
                return false;
            }
        }
        if($this->dailyHongBaoAddedNum($user_id, $hbt->id) >= $hbt->daily_limit && $hbt->daily_limit){
            return false;
        }
        if($hbt->is_stock){
            $flag = $hongBaoTemplate->where('id', $hbt->id)
                ->where('stock', '>=', 1)
                ->decrement('stock');
            if(!$flag){
                return false;
            }
        }
        $hongBao->user_id = $user_id;
        $hongBao->template_id = $hbt->id;
        $hongBao->origin = $origin;
        $hongBao->type = $hbt->type;
        $hongBao->agent_city_id = $hbt->agent_city_id;
        $hongBao->shop_id = $hbt->shop_id;
        $hongBao->limit_money = $hbt->limit_point;
        $hongBao->limit_money = $hbt->limit_money;
        if(!empty($hbt->max_point)){
            $hongBao->point = rand($hbt->min_point, $hbt->max_point);
        }
        if(!empty($hbt->max_money)){
            $hongBao->money = rand($hbt->min_money * 100, $hbt->max_money * 100) / 100;
        }
        if(empty($hbt->validity)){
            $validity = 30;
        }else{
            $validity = $hbt->validity;
        }
        $hongBao->end_at = time() + $validity * 86400;
        $hongBao->save();
        return true;
    }
}
